<?php

namespace App\Http\Controllers\Wechat;

use App\DB\WechatMpGameDB;
use App\Http\Controllers\Controller;
use App\Model\Game;
use App\Model\Wechat;
use App\Model\WechatGame;
use App\Model\WechatMp;
use App\Model\WechatMpGame;
use Illuminate\Http\Request;

class MpGameController extends Controller
{
    /**
     * 获取公众号游戏信息
     *
     * @param Request $request
     * @return array
     */
    public function getMpGame(Request $request)
    {
        # 公众号游戏ID
        if(!$request->has('id')) {
            return $this->error(1, 'No found id!');
        }
        $id = $request->input('id');
        $data = WechatMpGame::select('id', 'create_time', 'wechat_mp_id', 'game_id', 'title', 'subtitle', 'thumb', 'content', 'win_where', 'win_value', 'win_odds', 'use_amount', 'day_use_amount', 'share_amount', 'share_use_amount')->find($id);
        if(!$data) {
            return $this->error(2, 'Data error!');
        }
        $data = $data->toArray();
        $response = [];
        $response['data'] = $data;
        return $this->success($response);
    }

    /**
     * 获取游戏奖励
     *
     * @return mixed
     */
    public function getGameReward(Request $request)
    {
        # 公众号活动ID
        if(!$request->has('id')) {
            return $this->error(1, 'No found id');
        }
        $id = $request->input('id');
        # 获得微信用户ID
        if(!$request->has('wechat_id')) {
            return $this->error(2, 'No found wechat_id');
        }
        $wechatId = $request->input('wechat_id');
        # 寻找用户的openid
        $wechat = Wechat::find($wechatId);
        if(!$wechat) {
            return $this->error(3, 'Data error');
        }
        $openid = $wechat->openid;
        $wechatMpGame = WechatMpGame::find($id);
        if(!$wechatMpGame) {
            return $this->error(5, 'Data error');
        }
        # 获取游戏信息
        $gameId = $wechatMpGame->game_id;
        $game = Game::find($gameId);
        if(!$game) {
            return $this->error(6, 'Data error');
        }
        $type = $game->type;
        # 获取活动信息
        $wechatMpId = $wechatMpGame->wechat_mp_id;
        $wechatMp = WechatMp::find($wechatMpId);
        if(!$wechatMp) {
            return $this->error(9, 'Data error');
        }
        $winWhere = $wechatMpGame->win_where; # 获奖条件[0=等于,1=大于,2=小于,3=不等于]
        $winValue = $wechatMpGame->win_value; # 获奖数值
        $winOdds = $wechatMpGame->win_odds; # 获奖概率

        # 返还数据
        $response = [];
        # 根据游戏类型，判断是否成功
        $response['success'] = true; # 游戏成功
        $response['winning'] = false; # 是否获奖
        # 如果不是纯抽奖游戏，则先判断游戏是否达到抽奖要求
        if($type != 1) {
            # 获得分数（时间）
            if(!$request->has('point')) {
                return $this->error(4, 'No found point');
            }
            $point = $request->input('point');
            switch ($winWhere) {
                # 等于
                case 0:
                    # 如果获得的分数不等于获奖数值，则返回游戏失败
                    if($point != $winValue) {
                        $response['success'] = false;
                    }
                    break;
                # 大于
                case 1:
                    # 如果获得的分数小于等于获奖数值，则返回游戏失败
                    if($point <= $winValue) {
                        $response['success'] = false;
                    }
                    break;
                # 小于
                case 2:
                    # 如果获得的分数大于等于获奖数值，则返回游戏失败
                    if($point >= $winValue) {
                        $response['success'] = false;
                    }
                    break;
                # 不等于
                case 3:
                    # 如果获得的分数大于等于获奖数值，则返回游戏失败
                    if($point == $winValue) {
                        $response['success'] = false;
                    }
                    break;
                default:
                    $response['success'] = false;
                    break;
            }
            # 如果游戏失败，则直接返回游戏失败信息，不参与抽奖
            if($response['success'] == false) {
                $response['message'] = 'Game is not success!';
                return $this->success($response);
            }
        }

        # 根据概率，得出一个随机数，决定是否中奖
        $rand = mt_rand(1,100);
        if($rand > $winOdds) {
            $response['message'] = 'Thank you for participating.';
            return $this->success($response);
        }
        # 需要记录及使用的数据
        $data = [
            'wechat_id' => $wechatId,
            'wechat_mp_id' => $wechatMpId,
            'wechat_mp_game_id' => $id,
            'openid' => $openid,
        ];
        # 添加商品领取记录，并减少库存
        $code = WechatMpGameDB::getWinCode($data);
        if(!$code) {
            return $this->error(10, 'Data error');
        }
        $response['winning'] = true; # 获奖
        $response['message'] = 'Game is success!';
        $response['code'] = $code;
        return $this->success($response);
    }

    /**
     * 判断是否超过玩儿游戏次数上限
     *
     * @param Request $request
     * @return bool
     */
    public function playGame(Request $request)
    {
        # 公众号游戏ID
        if(!$request->has('id')) {
            return $this->error(1, 'No found id');
        }
        $id = $request->input('id');
        if(!$request->has('wechat_id')) {
            return $this->error(2, 'No found wechat_id');
        }
        $wechatId = $request->input('wechat_id');
        # 游戏信息
        $wechatMpGame = WechatMpGame::find($id);
        $wechatMpId = $wechatMpGame->wechat_mp_id; # 微信公众账号ID
        $useAmount = $wechatMpGame->use_amount; # 游戏总使用次数
        $dayUseAmount = $wechatMpGame->day_use_amount; # 每日游戏使用次数

        # 用户玩儿游戏记录
        $wechatGame = WechatGame::where('wechat_id', $wechatId)->where('wechat_mp_game_id', $id)->first();
        if(!$wechatGame) {
            $data = [
                'wechat_id' => $wechatId,
                'wechat_mp_id' => $wechatMpId,
                'wechat_mp_game_id' => $id,
            ];
            $wechatGame = WechatGame::createWechatGame($data);
            if(!$wechatGame) {
                return $this->error(3, 'Data error!');
            }
        }
        else {
            # 如果参与时间不在今天，清空当日参与数
            if ($wechatGame->last_time < currentTime('Y-m-d')) {
                $wechatGame = $wechatGame->clearDayTotal($wechatGame->id);
                if(!$wechatGame) {
                    return $this->error(4, 'Data error!');
                }
            }
        }
        $responses = [];
        $responses['can_play'] = false;
        # 判断今日是否超过可玩游戏次数上限
        if($wechatGame->total > $useAmount || $wechatGame->day_total > $dayUseAmount) {
            $responses['message'] = 'You have exceeded the number of times you can play ';
            return $this->success($responses);
        }
        $result = $wechatGame->recordTimes($wechatGame->id);
        if(!$result) {
            return $this->error(5, 'Data error!');
        }
        $responses['can_play'] = true;
        $responses['message'] = 'You can play the game';
        return $this->success($responses);
    }

}
